package com.web.spider.youku.service.impl;

import com.web.spider.youku.entity.Page;
import com.web.spider.youku.service.IProcessService;
import com.web.spider.youku.util.HtmlUtil;
import com.web.spider.youku.util.LoadPropertyUtil;
import com.web.spider.youku.util.RegexUtil;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import java.util.regex.Pattern;

/**
 * @author cherrish
 * @name YouKuProcessService
 * @date 2019/4/6 18:12
 * @desc TODO
 */
public class YouKuProcessService implements IProcessService {
    private String allnumberRegex = "(?<=总播放数)[\\d,]+";
    public void process(Page page) {
        String content = page.getContent();
        HtmlCleaner htmlCleaner = new HtmlCleaner();
        //利用htmlCleaner对网页进行解析，得到根节点
        TagNode rootNode = htmlCleaner.clean(content);

        //如果是详情页
        if (page.getUrl().startsWith("http://www.youku.com/show_page")) {
            parseDetail(rootNode, page);
        } else {

        }

    }

    //解析电视剧详情页
    public void parseDetail(TagNode rootNode, Page page) {
        // /html/body/div[4]/div/div[1]/div[2]/div[2]/ul/li[11]
        //对XPath做相应的调整，使其有效，如果不该写，则使用debug模式，会发现evaluateXPath为[]
               //总播放数
        // String allnumber = HtmlUtil.getFieldByRegex(rootNode, parseAllNumber, allnumberRegex);
        String allnumber = HtmlUtil.getFieldByRegex(rootNode, LoadPropertyUtil.getYouKu("parseAllNumber"), LoadPropertyUtil.getYouKu("allnumberRegex"));
        //System.out.println("总播放数数量为:"+allnumber);
        page.setAllnumber(allnumber);

        //评论数
        String commentnumber = HtmlUtil.getFieldByRegex(rootNode, LoadPropertyUtil.getYouKu("parseCommentNumber"), LoadPropertyUtil.getYouKu("commentnumberRegex"));
        //System.out.println("总评论数量为:"+commentnumber);
        page.setCommentnumber(commentnumber);

        //赞
        String supportnumber = HtmlUtil.getFieldByRegex(rootNode, LoadPropertyUtil.getYouKu("parseSupportNumber"), LoadPropertyUtil.getYouKu("supportnumberRegex"));
        //System.out.println("总评论数量为:"+supportnumber);
        page.setSupportnumber(supportnumber);

        page.setDaynumber("0");
        page.setAgainstnumber("0");
        page.setCollectnumber("0");

        //Pattern numberPattern = Pattern.compile(regex,Pattern.DOTALL);
        Pattern numberPattern = Pattern.compile(LoadPropertyUtil.getYouKu("idRegex"), Pattern.DOTALL);
        page.setTvId("tvId_" + RegexUtil.getPageInfoByRegex(page.getUrl(), numberPattern, 1));
    }
}
